package com.zimmur.controller;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zimmur.common.AppModuleEnum;
import com.zimmur.common.EnumPointRule;
import com.zimmur.common.IDWorkFactory;
import com.zimmur.common.ReturnJsonEntity;
import com.zimmur.common.StatusCodeEnum;
import com.zimmur.model.account.User;
import com.zimmur.model.account.VerifyMobile;
import com.zimmur.service.IUserService;
import com.zimmur.service.IVerifyMobileService;
import com.zimmur.service.RedisCacheUtil;
import com.zimmur.service.account.ICouponService;
import com.zimmur.service.account.IPointLogService;
import com.zimmur.service.account.IUserMessageService;
import com.zimmur.service.account.IUserNewMessageService;
import com.zimmur.service.order.ICartService;
import com.zimmur.tenpay.util.MD5;
import com.zimmur.tools.DateUtils;
import com.zimmur.tools.PublicKey;
import com.zimmur.tools.RandomUtil;


@RestController  
@RequestMapping("/user")  
// /user/**
public class UserController extends BaseController {  
	private static Logger log=LoggerFactory.getLogger(UserController.class);
	 @Resource(name="userService")
	 private IUserService userService;  
	 
	 @Resource(name="verifyMobileService")
	 private IVerifyMobileService verifyMobileService;
	 @Resource
	 private IUserMessageService userMessageService;
	 @Resource
	 private ICartService cartService;
	 @Resource
     private IPointLogService pointLogService;
	 @Value("#{spingMvcProperties['public.key']}")
	 private String publicKey;
	 @Resource
	 private RedisCacheUtil<String> redisCacheUtil;
	 @Resource
	 private ICouponService couponService;
	 @Resource
	 private IUserNewMessageService userNewMessageService;
	 /**
	  * 账号密码登录
	  * @return
	  */
    @RequestMapping(value="/login",method=RequestMethod.POST)  
    public ReturnJsonEntity login(){
    	ReturnJsonEntity entity = new ReturnJsonEntity();
        String userName = getParam("account");
        String password = getParam("password");
        String deviceId = getParam("deviceId");
        try {
        	entity = userService.login(userName, password, deviceId,"");
            
		} catch (Exception e) {
			log.error(e.getMessage());
		}
        
        return entity; 
    }  
       
    /**
	  * 账号密码登录
	  * @return
	  */
   @RequestMapping(value="/verifyforother",method=RequestMethod.POST)  
   public ReturnJsonEntity loginForOther(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum statusCodeEnum = StatusCodeEnum.CODE100000;
		String openId = getParam("openId");
		// wx=微信 wb=微博
		String plateForm = getParam("plateForm");
		String deviceId = getParam("deviceId");
		// System.out.println("userName:"+userName+" password:"+password);
		try {
			entity = userService.login(openId, "", deviceId,plateForm);
			
		} catch (Exception e) {
			log.error(e.getMessage());
		}

		return entity; 
   }
	/**
	 * 用户注册
	 * @param request
	 * @param model
	 * @return
	 */
   @ResponseBody
   @RequestMapping(value="/register",method=RequestMethod.POST)  
   public ReturnJsonEntity register(){  
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum statusCodeEnum = null;
		VerifyMobile verifyMobile=null;
		String mobileNo = getParam("mobileNo", "");
		String verifyCode = getParam("verifyCode", "");
		String userName = getParam("userName", "");
		String nickName = getParam("nickName", "");
		String userPwd = getParam("userPwd", "");
		String inviteCode = getParam("inviteCode", "");
		String openId = getParam("openId", "");
		String platform = getParam("platform", "");
		try{
			if(!verifyCode.equals("")){
				verifyMobile=verifyMobileService.getInfoByMobileAndCode(mobileNo,verifyCode);
				if(verifyMobile != null){
					//检查用户名或手机号是否和userName相同
					User checkUser = userService.getUserInfoByUserName(userName, "");
					if(checkUser != null){
						statusCodeEnum = StatusCodeEnum.CODE200203;
					}else{
						//检查用户名或手机号是否和mobileNo相同
						checkUser = userService.getUserInfoByUserName(mobileNo, "");
						if(checkUser != null){
							statusCodeEnum = StatusCodeEnum.CODE200202;	
						}
					}
												
				}else{
					statusCodeEnum = StatusCodeEnum.CODE200201;
				}
			}else{
				statusCodeEnum = StatusCodeEnum.CODE200201;
			}
			
			if(statusCodeEnum == null){
				int nowUnixTime = DateUtils.getNowUnixTime();
				User user = new User();
				long userId=IDWorkFactory.getID(AppModuleEnum.Account);
				user.setUserId(userId+"");
				user.setMobileNo(mobileNo);
				user.setUserName(userName);
				user.setNickName(nickName);
				user.setUserIcon("");
				user.setUserPwd(MD5.MD5Encode(userPwd));
				user.setInviteCode(createInviteCode());
				user.setRegisterInviteCode(inviteCode);
				user.setCategoryCode("zk");
				user.setCategoryName("知客");
				user.setOccupation("买手");
				user.setIsValide(1);
				user.setRegisterDate(nowUnixTime);
				user.setIsApply(1);
				if(userService.registerUser(user, openId, platform)){
					verifyMobile.setIsverify(1);
					verifyMobile.setVerifydate(nowUnixTime);
					verifyMobileService.updateVerifyStatus(verifyMobile);
					int flag=0;
					try {
						//发放注册礼包
						flag = couponService.createCouponByMobileNo(mobileNo, "register");
					} catch (Exception e) {
						log.error("send coupon error"+e.getMessage());
					}
					statusCodeEnum = StatusCodeEnum.CODE000000;
					/*if(flag>0){
						try {
							// 推送消息
							UserMessage userMessage=new UserMessage();
							userMessage.setMessageId(IDWorkFactory.getID(AppModuleEnum.UserMessage));
							userMessage.setToUserId(userId);
							userMessage.setCreateDate(nowUnixTime);
							userMessage.setUserId(0L);
							userMessage.setMsgTitle("注册礼包发放成功");
							userMessage.setMsgContent("恭喜！您的注册礼包已发放成功，请到我的卡券里查看。");
							userMessage.setCategoryCode("notify");
							userMessage.setModuleId(Integer.valueOf(AppModuleEnum.UserCenter.getModuleId()));
							userMessage.setMsgType("text");
							userMessage.setDataId("0");
							userMessage.setIsRead(0);
							userMessage.setIsPush(0);
							userMessage.setMsgUrl("");
							userMessageService.addNewMessage(userMessage);
						} catch (Exception e) {
							log.error(e.getMessage());
						}
					}*/
				}else{
					statusCodeEnum = StatusCodeEnum.CODE100000;
				}
			}
		}catch(Exception er){
			log.error(er.getMessage());
			statusCodeEnum = StatusCodeEnum.CODE100000;
		}		
		
		entity.setCode(statusCodeEnum.getCode());
		entity.setMsg(statusCodeEnum.getMsg());
		return entity;
	}
	
	
	
	/**
	 * 生成邀请码
	 * @return
	 */
	private String createInviteCode(){
		return RandomUtil.createInviteCode();
		
	}
	/**
	 * 忘记密码 
	 * @return
	 */
	@RequestMapping(value="/modifypassword",method=RequestMethod.POST)
	public ReturnJsonEntity modifyPassword(){
		ReturnJsonEntity entity = new ReturnJsonEntity();
		StatusCodeEnum status=StatusCodeEnum.CODE100000;
		VerifyMobile verifyMobile=null;
		try{
			//获取当前时间，转为INT存储
	        Integer timeDate =DateUtils.getUnixTimeByDate(DateUtils.getNow());
			String verifyCode = getParam("verifyCode", "");   
			String mobileNo = getParam("mobileNo", "");
			String newUserPwd = getParam("newUserPwd");

			Integer resut=0;
			User user = new User();
			if(!verifyCode.equals("")){
				verifyMobile=verifyMobileService.getInfoByMobileAndCode(mobileNo,verifyCode);
				if(verifyMobile != null){
					user.setMobileNo(mobileNo);
					//根据帐号和手机号查找是否有此 帐号
					Long userId = userService.selectByUserNameAndMobileNo(user);
					if(userId == null){
						status = StatusCodeEnum.CODE200204;
					}else{
						user.setUserName("");
						user.setMobileNo("");
						user.setUserId(userId+"");
						user.setUserPwd(MD5.MD5Encode(newUserPwd));
						userService.delUserToken(userId+"");
						resut = userService.updateUserinfo(user);
					}
				}else{
					status = StatusCodeEnum.CODE200201;
				}
			}
			if(resut > 0){
				verifyMobile.setIsverify(1);
				verifyMobile.setVerifydate(timeDate);
				verifyMobileService.updateVerifyStatus(verifyMobile);
				status=StatusCodeEnum.CODE000000;
			}
		}catch(Exception er){
			log.error(er.getMessage());
			status=StatusCodeEnum.CODE100000;
		}
		entity.setCode(status.getCode());
		entity.setMsg(status.getMsg());
		return entity;
	}
}  